<template>
  <div class="user-add-or-update">
    <el-drawer :title="this.rowData ? '编辑角色' : '新增角色'" size="88%" :visible.sync="drawer" custom-class="demo-drawer" direction="rtl">
      <div class="demo-drawer__content">
        <div :style="cardHeightStyle" class="rightScrollNone">
          <el-form size="mini" ref="vendorRuleForm" :model="dataForm" :rules="rules">
            <el-row>
              <el-col :span="24">
                <el-form-item label="角色名称：" prop="name" :label-width="formLabelWidth">
                  <el-input v-model="dataForm.name" type="text" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="角色描述：" prop="remark" :label-width="formLabelWidth">
                  <el-input v-model="dataForm.remark" type="text" autocomplete="off" maxlength="10"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="控制权限：" :label-width="formLabelWidth">
                  <el-tree ref="tree" :data="roleOptions" show-checkbox node-key="id" :default-checked-keys="nowchecklist" :props="defaultProps" @check="currentChecked"> </el-tree>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <div class="demo-drawer__footer">
          <el-button size="mini" @click="cancelForm">取 消</el-button>
          <el-button size="mini" type="primary" :loading="loading" @click="dataFormSubmit">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { addRoleApi, editRoleApi, roleMenusApi } from '../../../api/system'
import { notHavNumAndSymbol } from '@/utils/validate.js'

export default {
  data() {
    var validaName = (rule, value, callback) => {
      if (value && !notHavNumAndSymbol(value)) {
        callback(new Error('用户名只能为汉字或字母'))
      } else {
        callback()
      }
    }
    return {
      nowchecklist: [], // 已经选中的数组
      defaultProps: {
        children: 'children',
        label: 'title',
      },
      qxdata: [],
      showNumInput: false,
      showRefBtn: false,
      refNum: 0,
      dataForm: {
        name: '', // 角色名称
        remark: '', // 选中key集合
        f_code: [],
      },
      rowData: null,
      //cityOptions: citys.options,
      formLabelWidth: '95px',
      loading: false,
      drawer: false,
      statusOptions: [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 },
      ],
      roleOptions: [],
      rules: {
        name: [
          { required: true, message: '角色名不能为空', trigger: 'blur' },
          { validator: validaName, trigger: 'blur' },
        ],
      },
    }
  },
  mounted() {
    this.getinitialrole()
  },
  computed: {
    cardHeightStyle() {
      let documentClientHeight = document.body.clientHeight
      const height = documentClientHeight - 80 - 80
      return {
        height: height + 'px',
        'overflow-y': 'scroll',
        'padding-right': '20px;',
      }
    },
  },
  methods: {
    getinitialrole() {
      // 获取初始化的权限
      roleMenusApi({})
        .then((res) => {
          this.roleOptions = res.data
        })
        .catch((e) => {})
    },
    currentChecked(nodeObj, SelectedObj) {
      this.dataForm.power_code = SelectedObj.checkedKeys
      this.dataForm.f_code = SelectedObj.halfCheckedKeys
      if (nodeObj.title != '查看' && SelectedObj.halfCheckedNodes.length > 0) {
        SelectedObj.halfCheckedNodes[0].children.forEach((item) => {
          if (item.title == '查看') {
            this.$nextTick(() => {
              this.$refs.tree.setChecked(item.id, true, false)
            })
          }
        })
      } else if (nodeObj.title == '查看' && SelectedObj.halfCheckedNodes.length > 0) {
        // 对选中查看后取消的情况做处理
        if (SelectedObj.checkedKeys.length > 0 && SelectedObj.checkedKeys.indexOf(nodeObj.id) <= -1) {
          this.$refs.tree.setChecked(nodeObj.id, true, false)
          this.$message.warning('勾选其他选项后查看无法取消')
        }
      }
    },
    reportAdd(params) {
      const p = {
        name: params.name, // 角色名称
        remark: params.remark, // 选中key集合
        f_code: JSON.stringify(params.f_code),
        power_code: JSON.stringify(params.power_code),
      }
      return addRoleApi(p)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('保存成功')
          }
        })
        .catch((res) => {
          this.$message.error('保存失败')
        })
    },
    reportUpdate(params) {
      const p = {
        id: this.rowData.id,
        name: params.name, // 角色名称
        remark: params.remark, // 选中key集合
        f_code: JSON.stringify(params.f_code),
        power_code: JSON.stringify(params.power_code),
      }
      // params.id = this.rowData.id;
      return editRoleApi(p)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('保存成功')
          }
        })
        .catch((res) => {
          this.$message.error('保存失败')
        })
    },
    dataFormSubmit() {
      this.$refs.vendorRuleForm.validate((flag) => {
        if (flag) {
          const data = this.dataForm
          var request = this.rowData ? this.reportUpdate(data) : this.reportAdd(data)
          request
            .then((d) => {
              this.cancelForm()
              this.$emit('refreshList')
            })
            .catch((d) => {
              this.cancelForm()
            })
        }
      })
    },
    cancelForm() {
      this.cleanInfo()
      this.loading = false
      this.drawer = false
    },
    open(row, role) {
      row ? (this.nowchecklist = row.power_code) : (this.nowchecklist = [])
      if (this.drawer) {
        return
      }
      this.roleOptions = role
      console.log('this.', this.roleOptions)
      this.rowData = row || null
      this.drawer = true
      this.openHook()
    },
    clearData() {
      this.$refs.vendorRuleForm.resetFields()
    },
    cleanInfo() {
      this.dataForm.name = ''
      this.dataForm.power_code = []
      this.nowchecklist = []
      this.$nextTick(function () {
        //Dom更新完毕
        this.$refs.tree.setCheckedKeys([])
      })
    },
    openHook() {
      this.$nextTick((a) => {
        this.showNumInput = false
        this.refNum = 60 * 5 + 1
        this.clearData()
        if (this.rowData) {
          // 修改
          for (let key in this.dataForm) {
            if (key != 'emailCode') {
              this.dataForm[key] = this.rowData[key]
            }
          }
        } else {
          this.loading = false
        }
      })
    },
  },
}
</script>
<style lang="scss">
.user-add-or-update {
  .el-tag {
    position: relative;
    right: 5px;
    z-index: 1;
    height: 40px;
    line-height: 40px;
    border-radius: 0 5px 5px 0;
    padding-left: 15px;
  }

  .my-email {
    .el-input__inner {
      border-radius: 5px 0 0 5px;
    }
  }
}

/*

  */

.fileInput {
  padding-right: 0;
}
</style>
